<?php

namespace app\job;

use Illuminate\Database\Capsule\Manager as DB;

class Goods
{
    /**
     * 商品自动上架
     */
    public function autoshow(\QueueJob $job, $data){
        $newData = json_decode(json_encode($data,256), true);
        try {
            $goods = \goodsModel::query()->withoutGlobalScope('dianpu_id')->find($newData['goods_id']);
            if (!$goods){
                throw new \Exception('商品不存在');
            }
            if ($goods->status == 'down') {
                DB::transaction(function () use ($goods) {
                    $goods->status = 'up';
                    $goods->save();
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \Log::out('queue-' . get_class() . '-autoshow' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    /**
     * 商品自动下架
     */
    public function autohide(\QueueJob $job, $data){
        $newData = json_decode(json_encode($data,256), true);
        try {
            $goods = \goodsModel::query()->withoutGlobalScope('dianpu_id')->find($newData['goods_id']);
            if (!$goods){
                throw new \Exception('商品不存在');
            }
            if ($goods->status == 'up') {
                DB::transaction(function () use ($goods) {
                    $goods->status = 'down';
                    $goods->save();
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \Log::out('queue-' . get_class() . '-autohide' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

}

